<?php


namespace Beike\Libraries;

use Beike\Models\AdminUser;
use Beike\Models\ProductSku;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Auth;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Plugin\Repertory\Services\InventoryService;

class CSVImport implements ToCollection, WithHeadingRow
{
    public function collection(Collection $rows)
    {
        $admin_id = Auth::guard(AdminUser::AUTH_GUARD)->id();
        $service = new InventoryService();
        foreach ($rows as $row)
        {
            $one_sku = ProductSku::query()->where('id', $row['id']);
            $sku = $one_sku->first();
            if($sku->product_id && is_numeric($row['change'])){
                $is_zero = ($row['change'] + $sku->quantity) >= 0;
                $new_change = $is_zero ? $row['change']:abs($sku->quantity);
                if($sku->quantity == 0 && $row['change'] < 0){
                }else{
                    $one_sku->increment('quantity', $new_change);
                    $service->inventoryLog($admin_id, $sku->sku, $sku->product_id, $new_change, 'edit');
                }
            }
        }
    }

//    public function rules(): array
//    {
//        return [
//            'ID' => 'required',
//            'Change' => 'required',
//            'Change' => 'numeric',
//            // ...
//        ];
//    }
//
//    public function customValidationMessages()
//    {
//        return [
//            'ID.required' => 'ID字段是必填的',
//            'Change.required' => 'Add/Reduce字段必须是必填',
//            'Change.numeric' => 'Add/Reduce字段必须是数字',
//            // ...
//        ];
//    }
//    public function onError(\Throwable $e)
//    {
//        throw new ValidationException($e->validator);
//    }
}
